package com.zhiwei.gateway.config;

import com.google.common.collect.Iterables;
import com.zhiwei.gateway.filter.JwtAuthenticationTokenFilter;
import com.zhiwei.gateway.service.WhiteListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;

/**
 * 访问页面安全配置：表单登录认证
 * EnableWebSecurity：开启spring security安全认证
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private WhiteListService whiteListService;

    /**
     * 安全配置
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<String> whiteLists = whiteListService.queryValidWhiteList();
        String[] whiteListArray = Iterables.toArray(whiteLists, String.class);
        http.authorizeRequests()
                .antMatchers(whiteListArray).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().disable() //禁止表单登陆
                .csrf().disable()
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
}